using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

namespace Decav.Transactions
{
    /// <summary>
    /// Handles the standard EventHandler and updates target properties when the event fires.
    /// </summary>
    public class EventHandlerDataBindEventAdapter : IDataBindEventAdapter
    {
        #region Internal
        private class UpdateProxy : IDisposable
        {
            public UpdateProxy(BindingTarget source, BindingTarget target)
            {
                _source = source;
                _target = target;
                source.UpdatedEvent.AddEventHandler(source.Target, (EventHandler)Handle);
            }

            private BindingTarget _source;
            private BindingTarget _target;

            private void Handle(object sender, EventArgs e)
            {
                _target.Value = _source.Value;
            }

            #region IDisposable Members

            public void Dispose()
            {
                _source.UpdatedEvent.RemoveEventHandler(_source.Target, (EventHandler)Handle);
            }

            #endregion
        }
        #endregion

        private readonly Collection<UpdateProxy> _proxies = new Collection<UpdateProxy>();

        #region IDataBindEventAdapter Members

        public void Bind(BindingTarget source, BindingTarget target)
        {
            if (source.UpdatedEvent != null)
                _proxies.Add(new UpdateProxy(source, target));
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            foreach (UpdateProxy proxy in _proxies)
                proxy.Dispose();
        }

        #endregion
    }
}
